package com.zjh.workflow.flowable.controller;


import com.zjh.common.entity.Response;
import com.zjh.common.exception.ServiceException;
import com.zjh.workflow.flowable.entity.TaskInputParam;
import com.zjh.workflow.flowable.entity.WorkflowProcessInstance;
import com.zjh.workflow.flowable.entity.vo.HighLightElementVO;
import com.zjh.workflow.flowable.entity.vo.NodeDetailVO;
import com.zjh.workflow.flowable.service.ProcessInstanceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


@Api("流程实例")
@RestController
@Slf4j
@RequestMapping("/WorkFlow/instance")
public class ProcessInstanceController {


    @Resource
    private ProcessInstanceService processInstanceService;


    @Resource
    private RuntimeService runtimeService;


    @Resource
    private HistoryService historyService;




    @ApiModelProperty(value = "启动流程", notes = "根据流程定义Id 启动一个实例")
    @PostMapping("/newInstance")
    public Response<String> newInstanceByProcessId(@RequestBody TaskInputParam taskInputParam) {
        ProcessInstance instance = processInstanceService.newProcessInstance(taskInputParam);
        return Response.success(instance.getProcessInstanceId());
    }


    @ApiModelProperty(notes = "获取正在运行的流程实例")
    @GetMapping("/getAllProcessInstance")
    public Response<List<WorkflowProcessInstance>> getAllProcessInstance() {
        List<WorkflowProcessInstance> runningInstancesByProcessId = processInstanceService.getAllRunningInstances();

        return Response.success(runningInstancesByProcessId);
    }

    @ApiModelProperty(notes = "获取已经结束的历史流程")
    @GetMapping("/getAllHistoryProcessInstance")
    public Response<List<WorkflowProcessInstance>> getAllHistoryProcessInstance() {
        List<WorkflowProcessInstance> historicProcessInstances = processInstanceService.getAllHistoryInstances();

        return Response.success(historicProcessInstances);
    }


    @ApiModelProperty(notes = "根据ProcessId，获取流程实例")
    @GetMapping("/getByProcessId")
    public Response<List<WorkflowProcessInstance>> getProcessInstancesByProcessId(@RequestParam("processId") String processId) {
        List<WorkflowProcessInstance> runningInstancesByProcessId = processInstanceService.getRunningInstancesByProcessId(processId);

        return Response.success(runningInstancesByProcessId);
    }


    @ApiModelProperty(notes = "根据 processInstanceId 获取TaskId")
    @GetMapping("/getTaskListByProcessId")
    public Response<List<String>> getTaskIdsByProcessId(@RequestParam("processId") String processId) {
        List<String> taskIds = processInstanceService.getCurrentTaskIdsByProcessInstanceId(processId);

        return Response.success(taskIds);
    }


    @ApiModelProperty(notes = "根据流程实例Id 当前实例 流程状态图d")
    @GetMapping("/getFlowStatusImage")
    public Response<String> getFlowStatusImage(HttpServletResponse httpServletResponse, @RequestParam("instanceId") String instanceId) throws IOException {

        String base64Url = processInstanceService.genProcessDiagrams(instanceId, httpServletResponse);

        return Response.success(base64Url);
    }

    @ApiModelProperty(notes = "根据流程实例Id 当前实例 活动节点")
    @GetMapping("/getActiveNodes")
    public Response<HighLightElementVO> getActiveNodes(@RequestParam("instanceId") String instanceId) throws IOException {

        HighLightElementVO highLightedFlows = processInstanceService.getHighLightedFlows(instanceId);

        return Response.success(highLightedFlows);
    }

    @ApiModelProperty(notes = "根据流程Id 级联删除所有历史信息")
    @PostMapping("/history/deleteByProcessInstanceId")
    public Response<Void> deleteAllHistoryDataSafe(@RequestParam("processInstanceId") String processInstanceId) {


        // 删除历史流程实例（会自动级联删除相关历史数据）
        historyService.deleteHistoricProcessInstance(processInstanceId);

        // 确保删除所有相关历史任务
        List<HistoricTaskInstance> tasks = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInstanceId)
                .list();
        tasks.forEach(task -> historyService.deleteHistoricTaskInstance(task.getId()));

        return Response.success("删除流程成功", null);
    }

    @ApiOperation(value = "根据流程Id级联删除所有历史信息")
    @PostMapping("/running/deleteByProcessInstanceId")
    public Response<Void> deleteAllRunningInstanceDataSafe(@RequestParam("processInstanceId") String processInstanceId) {


        // 删除正在运行的流程实例（及相关的运行时数据）
        try {
            runtimeService.deleteProcessInstance(processInstanceId, "手动删除原因");
        } catch (Exception e) {
            throw new ServiceException("流程实例不存在: " + processInstanceId);
        }

        // 确保删除所有相关历史任务
        List<HistoricTaskInstance> tasks = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInstanceId)
                .list();
        tasks.forEach(task -> historyService.deleteHistoricTaskInstance(task.getId()));

        return Response.success("删除流程成功", null);
    }

    /**
     * 获取节点详情
     */
    @GetMapping("/nodeDetail/{flowId}/{activityId}")
    public Response<NodeDetailVO> getNodeDetails(
            @PathVariable String flowId,
            @PathVariable String activityId) {

        NodeDetailVO nodeDetails = processInstanceService.getNodeDetails(flowId, activityId);

        return Response.success(nodeDetails);
    }

}
